﻿@page "/"
@using Microsoft.AspNetCore.Http
@using Microsoft.AspNetCore.Identity;
@using BlazorBlogs.Data;
@using BlazorBlogs.Data.Models;
@using static Toolbelt.Blazor.HeadElement.MetaElement
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject UserManager<ApplicationUser> _UserManager
@inject SearchState SearchState
@inject InstallUpdateState _InstallUpdateState
@inject IConfiguration _configuration
@inject IHttpContextAccessor httpContextAccessor
@inject IHeadElementHelper HeadElementHelper
@inject DisqusState DisqusState
@inject NavigationManager NavigationManager
@inherits OwningComponentBase<BlogsService>
<Title>Blazor-Blogs</Title>
<Meta Property="og:title" Content="Blazor-Blogs" />
<RadzenDropDown AllowClear="true"
                AllowFiltering="true"
                FilterCaseSensitivity="FilterCaseSensitivity.CaseInsensitive"
                @bind-Value="SearchState.CurrentCategoryID" Multiple="false"
                Placeholder="Search Category..."
                Data="@colCategorys" TextProperty="Title"
                ValueProperty="CategoryId"
                Style="width:200px;"
                Change="@(args => ChangeCategory(args, "DropDown"))" />
<br />
<br />
<!-- Show the blogs -->
@if (UserIsAnAdmin)
{
    <button type="button" class="btn btn-primary" @onclick="NewBlog">New Blog</button>
    <br />
    <br />
}
@if (colBlogs.Blogs.Count == 0)
{
    <h2>No items returned</h2>
}
else
{
    @foreach (var blog in colBlogs.Blogs)
    {
        <a href="ViewBlogPost/@blog.BlogId"><h2>@blog.BlogDate.ToShortDateString() - @blog.BlogTitle</h2></a>
        <div class="form-group">
            @((MarkupString)blog.BlogSummary)
        </div>
        <hr />
    }
}
<br />
<BlogAdministration @ref="BlogAdministrationControl" BlogUpdated="BlogUpdatedEvent" />
<LicenseTerms @ref="LicenseTermsControl" />
@if (!LoadingBlogs)
{
    @if (ShowPreviousButton)
    {
        <button class="btn btn-warning"
                @onclick="Previous">
            <b>&#x3C;</b>
        </button>
    }
    @if (ShowNextButton)
    {
        <button class="btn btn-warning"
                @onclick="Next">
            <b>&#x3E;</b>
        </button>
    }
}
else
{
    <RadzenProgressBar Value="100" ShowValue="false" Mode="ProgressBarMode.Indeterminate" Style="margin-bottom: 20px" />
}
<br />
<br />
<div style="text-align:right">
    <button class="btn btn-link"
            @onclick="showTermsOfUse">
        Terms Of Use
    </button> |
    <button class="btn btn-link"
            @onclick="showPrivacyStatement">
        Privacy Statement
    </button>
</div>
@code {
    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }

    BlogAdministration BlogAdministrationControl;
    LicenseTerms LicenseTermsControl;
    bool LoadingBlogs = false;

    string ADMINISTRATION_ROLE = "Administrators";
    List<CategoryDTO> colCategorys = new List<CategoryDTO>();

    BlogsPaged colBlogs =
        new BlogsPaged()
        {
            Blogs = new List<Blogs>(),
            BlogCount = 0
        };

    bool ShowPreviousButton
    {
        get
        {
            return (SearchState.CurrentPage > 1);
        }
    }

    bool ShowNextButton
    {
        get
        {
            return (
                (colBlogs.BlogCount > (SearchState.CurrentPage * 5))
                );
        }
    }

    bool UserIsAnAdmin = false;
    System.Security.Claims.ClaimsPrincipal CurrentUser;

    protected override async Task OnInitializedAsync()
    {
        if (SearchState.CurrentPage == 0)
        {
            SearchState.CurrentPage = 1;
        }

        if (SearchState.CurrentCategoryID == null)
        {
            SearchState.CurrentCategoryID = "0";
        }

        // Get the current user
        CurrentUser = (await authenticationStateTask).User;

        if (CurrentUser.Identity.IsAuthenticated)
        {
            var Current_User = await _UserManager.FindByNameAsync(CurrentUser.Identity.Name);

            UserIsAnAdmin = await _UserManager.IsInRoleAsync(Current_User, ADMINISTRATION_ROLE);
        }

        colCategorys = await @Service.GetCategorysAsync();

        // We access BlogsService using @Service
        colBlogs = await @Service.GetBlogsAsync(SearchState.CurrentPage, Convert.ToInt32(SearchState.CurrentCategoryID));

        DisqusState.SetDisplayDisqus(false);
    }

    void NewBlog()
    {
        BlogAdministrationControl.AddNewBlog();
    }

    async Task BlogUpdatedEvent()
    {
        LoadingBlogs = true;
        StateHasChanged();

        colBlogs = await @Service.GetBlogsAsync(SearchState.CurrentPage, Convert.ToInt32(SearchState.CurrentCategoryID));

        LoadingBlogs = false;
        StateHasChanged();
    }

    async Task ChangeCategory(object value, string name)
    {
        LoadingBlogs = true;
        StateHasChanged();

        SearchState.CurrentPage = 1;
        SearchState.CurrentCategoryID = (value == null) ? "0" : value.ToString();

        colBlogs = await @Service.GetBlogsAsync(SearchState.CurrentPage, Convert.ToInt32(SearchState.CurrentCategoryID));

        LoadingBlogs = false;
        StateHasChanged();
    }

    void showTermsOfUse()
    {
        LicenseTermsControl.OpenPopup("TermsOfUse");
    }

    void showPrivacyStatement()
    {
        LicenseTermsControl.OpenPopup("PrivacyStatement");
    }

    async Task Previous()
    {
        LoadingBlogs = true;
        StateHasChanged();

        if (SearchState.CurrentPage > 1)
        {
            SearchState.CurrentPage = SearchState.CurrentPage - 1;
            colBlogs = await @Service.GetBlogsAsync(SearchState.CurrentPage, Convert.ToInt32(SearchState.CurrentCategoryID));
        }

        LoadingBlogs = false;
        StateHasChanged();
    }

    async Task Next()
    {
        LoadingBlogs = true;
        StateHasChanged();

        SearchState.CurrentPage = SearchState.CurrentPage + 1;
        colBlogs = await @Service.GetBlogsAsync(SearchState.CurrentPage, Convert.ToInt32(SearchState.CurrentCategoryID));

        LoadingBlogs = false;
        StateHasChanged();
    }
}